/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="phase-associated-component">
    <div class="phase-box" v-for="(item, index) in phaseList" :key="index">
      <div class="single-phase" @click="selectPhase(index, item)" :class="preselectPhase == item.id ? 'single-phase-select' : ''">
        <!-- <div class="ped-icon">
          <div v-for="(side, index) in item.peddirection" :key="'peddir-' + index">
            <PatternWalkSvg :Data="getshowped(side)" Width="42" Height="44" />
          </div>
        </div> -->

        <div class="phase-icon" v-if="item.direction">
          <xdr-dir-selector Width="44px" Height="44px" :showlist="getShowlist(item.direction)" :roadDirection="roadDirection"></xdr-dir-selector>
        </div>
        <div class="delete-phase-icon" @click="handleDeletePhase(index, item)">
          <i class="el-icon-close"></i>
        </div>
      </div>
      <div class="single-phase-name">{{$t('openatccomponents.channelizationmap.phase') + item.id}}</div>
    </div>
    <div class="phase-box">
      <div class="single-phase add-phase" @click="handleAddPhase()">
        <i class="iconfont icon-fangda" :class="{'add-disabled': !isCanAdd}"></i>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import PhaseDataModel from '../../IntersectionMap/crossDirection/utils.js'
// import PatternWalkSvg from 'openatc-components/package/kisscomps/components/PatternWalkSvg'
export default {
  name: 'phase-associated-component',
  data () {
    return {
      preselectPhase: -1,
      id: 1,
      isCanAdd: true
    }
  },
  components: {
    // PatternWalkSvg
  },
  props: {
    editData: {
      type: Object
    },
    phaseAssociatedMap: {
      type: Map
    }
  },
  computed: {
    ...mapState({
      phaseList: state => state.globalParam.tscParam.phaseList,
      roadDirection: state => state.globalParam.roadDirection
    })
  },
  watch: {
    phaseList: {
      handler: function (list) {
        if (list.length >= 40) {
          this.isCanAdd = false
        } else {
          this.isCanAdd = true
        }
      },
      deep: true
    },
    editData: {
      handler: function (editobj) {
        // console.log('editobj', editobj)
        if (editobj.phaseid !== undefined) {
          this.preselectPhase = editobj.phaseid
        } else {
          this.preselectPhase = -1
        }
      },
      deep: true
    }
  },
  methods: {
    selectPhase (index, item) {
      let direction = this.editDirPosToPhaseDireaciton(this.editData.icondireid, this.editData.lanePosition)
      // 校验同方位车道不能关联不同相位
      if (this.checkSameDirectionPhase(item.id, direction) === false) return
      // 关联相位
      this.preselectPhase = item.id
      // 组合现有和之前的相位 direction，并去重
      item.direction = Array.from(new Set([...item.direction, ...direction]))
      this.$emit('selectPhase', this.preselectPhase, direction)
    },
    changeDirection (choosedicon) {
      for (let i = 0; i < this.phaseList.length; i++) {
        if (this.phaseList[i].id === choosedicon.phaseid) {
          let direction = this.editDirPosToPhaseDireaciton(choosedicon.icondireid, choosedicon.lanePosition)
          // 校验同方位车道不能关联不同相位
          if (this.checkSameDirectionPhase(choosedicon.phaseid, direction) === false) return
          // 组合现有和之前的相位 direction，并去重
          this.phaseList[i].direction = Array.from(new Set([...this.phaseList[i].direction, ...direction]))
          this.$emit('selectPhase', this.preselectPhase, direction)
        }
      }
    },
    editDirPosToPhaseDireaciton (laneDirArr, lanePos) {
      // 编辑的车道转向和方位，转化成相位的direction
      let phaseDireacitonArr = laneDirArr.map(lanedir => {
        if (lanePos === 1) {
          // 东
          return lanedir
        }
        if (lanePos === 2) {
          // 西
          return 4 * 1 + lanedir
        }
        if (lanePos === 3) {
          // 南
          return 4 * 3 + lanedir
        }
        if (lanePos === 4) {
          // 北
          return 4 * 2 + lanedir
        }
      })
      return phaseDireacitonArr
    },
    getShowlist (direction) {
      return direction.map(dir => {
        return {
          id: dir,
          color: '#606266'
        }
      })
    },
    getshowped (peddirection) {
      return {
        id: peddirection,
        name: this.PhaseDataModel.getSidePos(peddirection).name
      }
    },
    handleDeletePhase (index, row) {
      this.$confirm(this.$t('openatccomponents.phase.deletetip'),
        this.$t('openatccomponents.common.alarm'), {
          confirmButtonText: this.$t('openatccomponents.common.confirm'),
          cancelButtonText: this.$t('openatccomponents.common.cancel'),
          type: 'warning'
        }).then(() => {
        this.globalParamModel.deleteParamsByType('phaseList', index, 1)
        this.deleteRing(row)
        this.$message({
          type: 'success',
          message: this.$t('openatccomponents.common.deletesucess')
        })
        // 删除关联此行的并发相位
        this.handleDeleteConcurrent(row.id, [], row.concurrent)
        // 删除关联此相位的所有车道相位id
        this.handleDisassociatePhase(row.id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('openatccomponents.common.deletecancel')
        })
      })
    },
    handleDisassociatePhase (deletePhaseid) {
      // 删除相位后，解除相位关联
      this.$emit('handleDisassociatePhase', deletePhaseid)
    },
    handleAddPhase () {
      this.increaseId()
      if (this.globalParamModel.getParamLength('phaseList') >= 40) {
        this.$message.error(
          this.$t('openatccomponents.phase.mostdata')
        )
        return
      }
      var phaseInitData = {
        id: this.id,
        direction: [],
        peddirection: [], // 行人方向
        mingreen: 0,
        max1: 120,
        max2: 180,
        passage: 3,
        phasewalk: 0,
        pedclear: 0,
        yellow: 3,
        redclear: 2,
        flashgreen: 0,
        redyellow: 0,
        ring: 1,
        greenpulse: 5,
        redpulse: 10,
        vehiclethresh: 30,
        pedestrianthresh: 30,
        controltype: 0, // 控制类型
        concurrent: []
      }
      this.globalParamModel.addParamsByType('phaseList', phaseInitData)
      // this.id++
      this.editRing(phaseInitData)
      // 重新排序相位数组
      let phaseList = this.globalParamModel.getParamsByType('phaseList')
      phaseList.sort(this.compareProperty('id'))
    },
    compareProperty (property) {
      return function (a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    },
    increaseId () { // 实现id在之前的基础上寻找最小的
      let phaseList = this.globalParamModel.getParamsByType('phaseList')
      let phaseIdList = phaseList.map(ele => ele.id)
      let i = phaseList.length - 1
      if (i >= 0) {
        for (let j = 1; j <= 40; j++) {
          if (!phaseIdList.includes(j)) {
            this.id = j
            return
          }
        }
      }
    },
    deleteRing (row) {
      let patternList = this.globalParamModel.getParamsByType('patternList')
      let id = row.id
      let ring = row.ring - 1
      for (let pattern of patternList) {
        for (let i = 0; i < pattern.rings[ring].length; i++) {
          if (pattern.rings[ring][i].id === id) {
            pattern.rings[ring].splice(i, 1)
            pattern.cycle = pattern.cycle - 30
          }
        }
      }
    },
    editRing (value) {
      let patternList = this.globalParamModel.getParamsByType('patternList')
      let id = value.id
      for (let pattern of patternList) {
        let ring = {}
        ring.name = 'Phase ' + id
        ring.id = id
        ring.value = 30
        pattern.rings[0].push(ring)
        pattern.cycle = pattern.cycle + 30
      }
    },
    handleDeleteConcurrent (curid, curVal, oldVal) {
      // 删除关联的并发相位
      let phaseList = this.globalParamModel.getParamsByType('phaseList')
      for (let i = 0; i < oldVal.length; i++) {
        if (curVal.indexOf(oldVal[i]) === -1) {
          // 此项已被删除
          for (let j = 0; j < phaseList.length; j++) {
            if (phaseList[j].id === oldVal[i]) {
              let index = phaseList[j].concurrent.indexOf(curid)
              if (index !== -1) {
                phaseList[j].concurrent.splice(index, 1)
              }
            }
          }
        }
      }
    },
    checkSameDirectionPhase (curphaseid, curdirection) {
      // 校验同方向车道关联相位
      // console.log('phaseAssociatedMap', this.phaseAssociatedMap)
      let checkSame = true
      for (let [key, value] of this.phaseAssociatedMap) {
        if (curphaseid !== key) {
          for (let i = 0; i < value.length; i++) {
            if (value[i].index === this.editData.index) continue
            if (!value[i].direction || !value[i].direction.length) continue
            for (let j = 0; j < curdirection.length; j++) {
              if (value[i].direction.indexOf(curdirection[j]) !== -1) {
                checkSame = false
                this.$message.error(this.$t('openatccomponents.channelizationmap.associatedphaseerror'))
                break
              }
            }
          }
        }
      }
      return checkSame
    },
    getPedPhasePos () {
    // 行人相位信息
      this.sidewalkPhaseData = []
      this.phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
            // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.sidewalkPhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name
              })
            }
          })
        }
      })
      return this.sidewalkPhaseData
    }
  },
  created () {
    this.globalParamModel = this.$store.getters.globalParamModel
    this.PhaseDataModel = new PhaseDataModel()
    this.increaseId()
  },
  mounted () {
  },
  destroyed () {
  }
}
</script>
<style lang="scss">
</style>
